package com.graduate.controller;

import com.db.pojo.Picture;
import com.graduate.exception.BizException;
import com.graduate.exception.ExceptionEnum;
import com.graduate.service.PictureService;
import com.graduate.utils.BaseServiceUtils;
import com.graduate.utils.FileUtils;
import com.graduate.utils.RespBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;

@RestController
//@EnableAutoConfiguration
@RequestMapping("/image")
public class ImageController extends BaseServiceUtils {


    @Value("${file.path}")
    private String path;

    @Autowired
    private PictureService pictureService;

    @RequestMapping(value = "/imText",method = RequestMethod.POST)
    @ResponseBody
    public RespBody imageText(@RequestBody MultipartFile file, @RequestBody String id){

        return RespBody.success(path);
    }

    @RequestMapping(value = "/upload/file", method = RequestMethod.POST)
    @ResponseBody
    public RespBody saveFile(@RequestBody MultipartFile file, @RequestBody String id) {
        StringBuffer fileName = new StringBuffer();
        fileName.append(id);
        String type = file.getContentType();
        if ("image/png".equals(type)) {
            fileName.append(".png");
        } else if ("image/jpeg".equals(type)) {
            fileName.append(".jpeg");
        } else if ("image/gif".equals(type)) {
            fileName.append(".gif");
        } else {
            throw new BizException(ExceptionEnum.BODY_NOT_MATCH);
        }
        if (file.getSize() > 1024000L) {
            return RespBody.error("00","图片过大");
        }
        try {
            file.transferTo(new File(path, fileName.toString()));
            return RespBody.success();
        } catch (IOException e) {
            e.printStackTrace();
            return RespBody.error("保存失败");
        }
    }

    @RequestMapping(value = "/upload/base64", method = RequestMethod.POST)
    @ResponseBody
    public RespBody saveBase64(@RequestBody String base64Str) {
        StringBuffer fileName = new StringBuffer();
//        fileName.append(UUID.randomUUID().toString().replaceAll("-", ""));
        if (StringUtils.isEmpty(base64Str)) {
            return RespBody.error("file不可为空");
        } else if (base64Str.indexOf("data:image/png;") != -1) {
            base64Str = base64Str.replace("data:image/png;base64,", "");
            fileName.append(".png");
        } else if (base64Str.indexOf("data:image/jpeg;") != -1) {
            base64Str = base64Str.replace("data:image/jpeg;base64,", "");
            fileName.append(".jpeg");
        } else {
            return RespBody.error("请选择.png.jpg格式的图片");
        }
        File file = new File(path, fileName.toString());
        byte[] fileBytes = Base64.getDecoder().decode(base64Str);
        FileUtils.writeByteArrayToFile(file, fileBytes);
        return RespBody.success();
    }


//    @RequestMapping(value = "/get", produces = MediaType.IMAGE_JPEG_VALUE)
    @GetMapping(value = "/get", produces = MediaType.IMAGE_JPEG_VALUE)
//    @ResponseBody
    public byte[] getImageById(@RequestParam("id") String id) throws IOException {
        if ( StringUtils.isEmpty(id)) {
            throw new BizException(ExceptionEnum.PARAM_IS_NULL);
        }

        Picture picture = null;
        if (!StringUtils.isEmpty(id)) {
            if (id.length() > 32) {
                throw new BizException(ExceptionEnum.BODY_NOT_MATCH);
            }
            picture = pictureService.getPictureById(id);
        }

        String imageBase64 = picture.getContent();
        String originalBase64 = imageBase64.substring(imageBase64.indexOf(";base64,") + 8);
        File tempFile = new File(path, id+".jpeg");
        tempFile = FileUtils.base64ToFile(originalBase64, tempFile);
        FileInputStream inputStream = new FileInputStream(tempFile);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes, 0, inputStream.available());
        return bytes;
    }


    @RequestMapping(value = "/download/file", method = RequestMethod.POST)
    @ResponseBody
    public RespBody downoaldFile() {
        return RespBody.success();
    }
}
